package com.wfm.lock.readwriteandstamped;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 比较ReentrantReadWriteLock和StampedLock的性能
 * ReentrantReadWriteLock  156ms
 * StampedLock 29ms
 */
public class PerformanceComparison {
    private static final int READ_THREADS = 9;
    private static final int WRITE_THREADS = 1;
    private static final int OPERATIONS = 100000;

    public static void main(String[] args) throws InterruptedException {
        // 测试 ReentrantReadWriteLock 的性能
        ReentrantReadWriteLockExample rwLockExample = new ReentrantReadWriteLockExample();
        long rwLockStartTime = System.currentTimeMillis();
        testPerformance(rwLockExample);
        long rwLockEndTime = System.currentTimeMillis();
        System.out.println("ReentrantReadWriteLock 执行时间: " + (rwLockEndTime - rwLockStartTime) + " 毫秒");

        // 测试 StampedLock 的性能
        StampedLockExample stampedLockExample = new StampedLockExample();
        long stampedLockStartTime = System.currentTimeMillis();
        testPerformance(stampedLockExample);
        long stampedLockEndTime = System.currentTimeMillis();
        System.out.println("StampedLock 执行时间: " + (stampedLockEndTime - stampedLockStartTime) + " 毫秒");
    }

    private static void testPerformance(Object example) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(READ_THREADS + WRITE_THREADS);
        CountDownLatch latch = new CountDownLatch(READ_THREADS + WRITE_THREADS);

        // 启动写线程
        for (int i = 0; i < WRITE_THREADS; i++) {
            executor.submit(() -> {
                for (int j = 0; j < OPERATIONS; j++) {
                    if (example instanceof ReentrantReadWriteLockExample) {
                        ((ReentrantReadWriteLockExample) example).write();
                    } else if (example instanceof StampedLockExample) {
                        ((StampedLockExample) example).write();
                    }
                }
                latch.countDown();
            });
        }

        // 启动读线程
        for (int i = 0; i < READ_THREADS; i++) {
            executor.submit(() -> {
                for (int j = 0; j < OPERATIONS; j++) {
                    if (example instanceof ReentrantReadWriteLockExample) {
                        ((ReentrantReadWriteLockExample) example).read();
                    } else if (example instanceof StampedLockExample) {
                        ((StampedLockExample) example).read();
                    }
                }
                latch.countDown();
            });
        }

        latch.await();
        executor.shutdown();
    }
}